var Redis = require('Redis')
var Contracts = require('../Contracts')

var Streamers = require('../Streamers')
var RedisStorage = (function () {
    function RedisStorage() {
        this.ignoreMembersDefault = [
            'id', 
            'qualifiedName', 
            'schema'
        ];
        this.jsonFieldName = '_doc_json';
        this.createDefaultStreamer = function (field) {
            if(field.type === 'string') {
                return new Streamers.ToStringStreamer();
            } else {
                if(field.type === 'number') {
                    return new Streamers.NumberStreamer();
                } else {
                    return new Streamers.JsonStreamer();
                }
            }
        };
    }
    RedisStorage.prototype.getDocument = function (id, schema) {
        var key = this.generateKey(id, schema.getQualifiedName());
        return null;
    };
    RedisStorage.prototype.insertOrUpdate = function (doc, schema, callback) {
        var key = this.generateKey(doc.id, doc.getQualifiedName());
        var content = {
        };
        var that = this;
        var ignoreMembers = [];
        schema.fields.forEach(function (field) {
            var streamer;
            if(field.createStreamer) {
                streamer = field.createStreamer();
            }
            if(!streamer) {
                streamer = that.createDefaultStreamer(field);
            }
            var value = streamer.serialize(doc[field.name]);
            if(value != null) {
                content[field.name] = value;
                ignoreMembers.add(field.name);
            }
        });
        content[this.jsonFieldName] = this.toJson(doc, ignoreMembers);
        var client = Redis.createClient();
        client.HMSET(key, content, function (err, reply) {
            client.end();
            if(callback) {
                err ? callback(new Error(err)) : callback(null);
            }
        });
    };
    RedisStorage.prototype.toJson = function (doc, ignoreMembers) {
        var streamer = new Streamers.JsonStreamer(this.ignoreMembersDefault.concat(ignoreMembers));
        return streamer.serialize(doc);
    };
    RedisStorage.prototype.generateKey = function (id, schemaName) {
        return schemaName.getFullName() + '=' + id.toString();
    };
    return RedisStorage;
})();
exports.RedisStorage = RedisStorage;

